//
//  ListPageView.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/6/15.
//

import UIKit

enum SCROL_TYPE:Int {
    case V_SCROL
    case H_SCROL
}

let PAGE_TAG = 1000

class ListPageView: UIScrollView {
    var pageType:SCROL_TYPE!
    
    var myViews:Array<UIView>!
    
    init(frame: CGRect,type:SCROL_TYPE) {
        super.init(frame: frame)
        pageType = type
        self.isPagingEnabled = true
        self.bounces = false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setViews(views:Array<UIView>) {
        self.myViews = views
        self.updatePageViews(views: views)
    }
    func updatePageViews(views:Array<UIView>) {
        for obj in self.subviews {
            if obj.tag >= PAGE_TAG {
                obj.removeFromSuperview()
            }
        }
        for (index,obj) in views.enumerated() {
            let viewPoint:CGPoint = self.contentOffsetForPageType(index: index)
            
            obj.frame = CGRect.init(x: viewPoint.x, y: viewPoint.y, width: self.frame.size.width, height: self.frame.size.height)
            obj.tag = PAGE_TAG + index
            self.addSubview(obj)
        }
        self.contentSize = self.pageType == SCROL_TYPE.H_SCROL ? CGSize.init(width: self.frame.size.width * CGFloat(views.count), height: self.frame.size.height) : CGSize.init(width: self.frame.size.width, height: self.frame.size.height * CGFloat(views.count))
    }
    
    func scrollToIndex(pageIndex:Int,animated:Bool)  {
        self.setContentOffset(self.contentOffsetForPageType(index: pageIndex), animated: animated)
    }
    
    func contentOffsetForPageType(index:Int) -> CGPoint {
        let p:CGPoint!
        if self.pageType == SCROL_TYPE.H_SCROL {
            p = CGPoint.init(x: self.frame.size.width * CGFloat(index), y: 0)
        } else {
            p = CGPoint.init(x: 0, y: self.frame.size.height * CGFloat(index))
        }
        return p
    }
}
